import { Component, EventEmitter, OnInit, Output } from "@angular/core";
import { FormBuilder, FormControl, FormGroup } from "@angular/forms";
import { NzMessageService } from "ng-zorro-antd/message";
import { NzTreeNode } from "ng-zorro-antd/tree";
import { DictionaryItemService } from "../dictionary-item.service";

@Component({
  selector: "app-dictionary-item-edit",
  templateUrl: "./dictionary-item-edit.component.html",
  styles: []
})
export class DictionaryItemEditComponent implements OnInit {


  constructor(private formBuilder: FormBuilder,
              private msgSrv: NzMessageService,
              private dictionaryItemService: DictionaryItemService
  ) {
  }

  nzLoading = false;

  @Output() voted = new EventEmitter();

  validateForm!: FormGroup;

  // 是否编辑
  isUpdate = false;

  visible = false;
  // 主字典ID
  dictId;

  open(dictId): void {
    this.dictId = dictId;
    this.visible = true;
    this.isUpdate = false;
  }

  edit(param, dictId) {
    this.dictId = dictId;
    this.visible = true;
    this.isUpdate = true;

    if (param) {
      this.validateForm.patchValue(param);
    } else {
      this.validateForm.reset();
    }
  }

  close(): void {
    this.visible = false;
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    this.nzLoading = true;

    // 维护字典主表的ID
    this.validateForm.patchValue({ "dictionaryId": this.dictId });

    this.dictionaryItemService.update(this.validateForm.value).subscribe((res) => {

      this.nzLoading = false;

      if (res.code === 1) {
        this.msgSrv.success("保存完成");
        this.close();
        this.voted.emit();
      } else {
        this.msgSrv.error(res.message);
      }
    });
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
    return {};
  };

  getCaptcha(e: MouseEvent): void {
    e.preventDefault();
  }

  ngOnInit(): void {

    this.validateForm = this.formBuilder.group({
      id: [null],
      label: [null],
      value: [null],
      idx: [null],
      dictionaryId: [null]
    });

  }

  nzDisplayWith(node: NzTreeNode) {
    return node.title;
  }

  onChange($event: string): void {
    console.log($event);
  }

}
